﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Transactions;
using Tauren.File.DLL.Base;
using Tauren.File.DLL.FileDLL;
using Tauren.File.DLL.FileIODLL;
using Tauren.File.Entity.Config;
using Tauren.File.Entity.Enum;
using Tauren.File.Entity.Global;
using Tauren.File.Entity.Model;
using Tauren.File.Infrastructure.Common;

namespace Tauren.File.Service.FileVersionBLL
{
    public class TrackFileService : ITrackFileService
    {
        private IBaseDLL business;
        private FilePath filePath;
        public IFileIOBusiness IOBusiness { get; set; }
        private HttpContext context;
        public TrackFileService(IBaseDLL baseDLL, IConfiguration configuration, IHttpContextAccessor HttpContextAccessor)
        {
            business = baseDLL;
            ///获取配置文件中的数据
            filePath = configuration.Get<ApiVersionsConfig>().FilePath;
            context = HttpContextAccessor.HttpContext;
        }

        public string TrackFile(long fileid, string token)
        {
            if (string.IsNullOrEmpty(token)) return "";
            TrackConfig trackConfig = Common.ReadToken(token);
            if (trackConfig is null) return "";
            string body = GetBody(context: context);
            if (string.IsNullOrEmpty(body) || string.IsNullOrEmpty(trackConfig.TenantCode) || trackConfig.EmpId <= 0) return "";
            OutOfficeConfigModel fileData = JsonSerializer.DeserializeFromString<OutOfficeConfigModel>(body);
            TenantInformation tenantInformation = business.GetByCode<TenantInformation>(trackConfig.TenantCode);
            if (tenantInformation is null) return "";
            business.BuliderDbConnection(tenantInformation.files_Dbconnection);
            switch (fileData.status)
            {
                case TrackerStatus.MustSave:
                case TrackerStatus.Corrupted:
                    {
                        Files files = business.Get<Files>(id: fileid);
                        if (null != files)
                        {
                            FilesVersion filesVersion = IOBusiness.TrackFile(files: files, fileData: fileData);
                            using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadCommitted }))
                            {
                                var byt = Convert.FromBase64String(token);
                                files.Modifier = trackConfig.EmpId;
                                files.Modifdate = DateTime.Now;
                                filesVersion.Creator = trackConfig.EmpId;
                                filesVersion.Modifier = trackConfig.EmpId;
                                business.Update<Files>(model: files);
                                business.Add<FilesVersion>(filesVersion);
                                ts.Complete();
                            }
                        }
                    }
                    break;
                default: { } break;
            }
            return "{\"error\":0}";
        }
        public string GetBody(HttpContext context)
        {
            string body = "";
            try
            {
                using (var receiveStream = context.Request.Body)
                using (var readStream = new StreamReader(receiveStream))
                {
                    body = readStream.ReadToEndAsync().Result;
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return body;
        }
        /// <summary>
        /// 获取配置文件
        /// </summary>
        /// <param name="editType"></param>
        /// <param name="systemType"></param>
        /// <param name="fileid"></param>
        /// <returns></returns>
    }
}
